package com.carlinfo.back.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.eclipse.jdt.internal.compiler.batch.Main;

import com.alibaba.fastjson.JSONObject;
import com.carlinfo.common.servlet.BaseServlet;
import com.carlinfo.common.util.ConstantFinalUtil;
import com.carlinfo.userscenter.users.pojo.AAdmins;
import com.carlinfo.userscenter.users.service.IUsersService;
import com.carlinfo.userscenter.users.service.impl.UsersServiceImpl;

public class AdminsBackServlet extends BaseServlet
{
	private IUsersService usersService = new UsersServiceImpl();
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		String method = request.getParameter("method");
		if ("main".equalsIgnoreCase(method))
		{
			main(request, response);
		} else if ("welcome".equalsIgnoreCase(method))
		{
			welcome(request, response);
		} else if ("adminsUpdate".equalsIgnoreCase(method))
		{
			/* 管理员打开更新 */
			this.adminsUpdate(request, response);
		}else if("adminsUpdateSubmit".equalsIgnoreCase(method))
		{
			/* 管理员更新提交 */
			this.adminsUpdateSubmit(request,response);
		}
	}

	private void adminsUpdateSubmit(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		HttpSession session = request.getSession() ; 
		AAdmins admins = (AAdmins) session.getAttribute("adminsSess");

		Map<String, List<Object>> resultMap = this.proccedFileUpload(request);
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", admins.getId());
		admins = this.usersService.findOneAdminsService(condMap);
		
		String email = resultMap.get("email").get(0) + "";
		String trueName = resultMap.get("trueName").get(0) + "";
		String qq = resultMap.get("qq").get(0) + "";
		String phone = resultMap.get("phone").get(0) + "";
		String sex = resultMap.get("sex").get(0) + "";
		String status = resultMap.get("status").get(0) + "";
		/* 图片是二进制
		  返回值是字符串:*/
		   
		List<Object> fileList = resultMap.get("file");
		/* 如何将上传的文件存储下来
		 * fileList:放了一个输入流
		 * 
		 * 目标文件存储的位置:
		 * D:/班级/20180709/20180916-用户中心/代码/userscenter/WebContent/uploadfile/admins/2018-09-30/111.jpg
		 *  */
		String truePath = ConstantFinalUtil.CONFIG1_JSON.getString("truePath") ; 
		String relaPath = ConstantFinalUtil.CONFIG1_JSON.getString("relaPath") + "/admins/"
				+ this.dateUtil.dateToStr(new Date()) + "/" + fileList.get(1);
		File tarFile = new File(truePath + relaPath);
		this.logger.info("---上传文件的路径:{}--",tarFile.getAbsolutePath());
		/* 想拷贝
		  拷贝之前一定确认此文件的目录存在  */
		if(!tarFile.getParentFile().exists())
		{
			tarFile.getParentFile().mkdirs();
		}
		InputStream is = (InputStream) fileList.get(2);
		OutputStream os = new FileOutputStream(tarFile);
		this.ioUtil.copy(is, os);
		/* 数据库存储的是相对路径 */
		admins.setPhotoPath(relaPath);
		admins.setEmail(email);
		admins.setTrueName(trueName);
		admins.setQq(qq);
		admins.setPhone(phone);
		admins.setSex(Byte.valueOf(sex));
		admins.setStatus(Byte.valueOf(status));
		JSONObject resultJSON = this.usersService.updateOneAdminsService(admins);
		
		/* 将返回结果给jsp
		 * jsp点击更新提交的时候是ajax,不是表单提交跳转
		 * 给他一个JSON
		 *  */
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter() ; 
		out.println(resultJSON.toJSONString());
		out.flush();
		out.close();
	}
/**
 * 用来处理文件上传的值获取
 * @param request
 * @return
 */
	private Map<String, List<Object>> proccedFileUpload(HttpServletRequest request)
	{
		Map<String, List<Object>> resultMap = new HashMap<String, List<Object>>();
		/* 创建一个factory;硬盘基本的存储
		 * 上传临时文件放哪？ */
		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();
		/**
		 * 往最大作用域里放一个变量
		 * 只负责取
		 * fileUpload放的
		 */
		// Configure a repository (to ensure a secure temp location is used)
		ServletContext servletContext = this.getServletConfig().getServletContext();
		File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
		factory.setRepository(repository);

		//创建一个上传文件的解析器
		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		try
		{
			//解析request
			// Parse the request
			List<FileItem> items = upload.parseRequest(request);
			for (Iterator iterator = items.iterator(); iterator.hasNext();)
			{
				FileItem fileItem = (FileItem) iterator.next();
				/* 表单中所有的控件都放在了List中，封装到了fileItem中 */
				if(fileItem.isFormField())
				{
					/* 是一个普通控件 */
					String name = fileItem.getFieldName();
					String value = fileItem.getString();
					/* 因为一个文件上传有四部分，硬要往map里面放，所有就写了一个List */
					List<Object> resultList = new ArrayList<Object>();
					resultList.add(value);
					resultMap.put(name, resultList);
				}else 
				{
					/* 上传的文件 表单中input name的值 */
					String  name = fileItem.getFieldName();
					/*上传的文件的本身名字*/
					String fileName = fileItem.getName() ;
					/*MIME类型*/
					String contentType = fileItem.getContentType();
					
					/* 将他们放到list中，然后再把list放到map中 */
					List<Object> resultList = new ArrayList();
					resultList.add(name);
					resultList.add(fileName);
					resultList.add(fileItem.getInputStream());
					resultMap.put(name, resultList);
				}
				
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return resultMap;
	}
/**
 * 修改提交的页面跳转
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
	private void adminsUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		/* 获取Session */
		HttpSession session = request.getSession();
		AAdmins admins = (AAdmins) session.getAttribute("adminsSess");

		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", admins.getId());
		admins = this.usersService.findOneAdminsService(condMap);
		request.setAttribute("admins", admins);

		/* 打开登陆页 */
		String path = "/WEB-INF/jsp/back/admins/adminsUpdate.jsp";
		/* 服务器端跳转 */
		request.getRequestDispatcher(path).forward(request, response);
	}

	private void welcome(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String path = "/WEB-INF/jsp/back/admins/welcome.jsp";
		request.getRequestDispatcher(path).forward(request, response);
		;
	}

	private void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String path = "/WEB-INF/jsp/back/admins/main.jsp";
		request.getRequestDispatcher(path).forward(request, response);
//		response.sendRedirect(path);
	}

}
